package com.xjx.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.xjx.config.OssConfig;
import com.xjx.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Autowired
    private OssConfig ossConfig;
    @Override
    public String upload(MultipartFile file) {
        // 1. 检查文件是否有效
        if (file == null || file.isEmpty()) {
            return "上传失败：文件为空";
        }

        // 2. 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFilename = UUID.randomUUID().toString().replace("-", "") + suffix;

        // 3. 获取 OSS 配置和上传路径
        String endpoint = ossConfig.getEndpoint();
        String accessKey = ossConfig.getAccessKey();
        String secret = ossConfig.getSecret();
        String bucket = ossConfig.getBucket();
        String dir = ossConfig.getDir();

        // 移除路径开头和结尾的斜杠，以确保 ObjectKey 格式正确
        String normalizedDir = dir.replaceAll("^/|/$", "");

        String objectKey = normalizedDir + "/" + newFilename;

        OSS ossClient = null;
        InputStream inputStream = null;
        try {
            // 4. 创建 OSS 客户端并上传文件
            ossClient = new OSSClientBuilder().build(endpoint, accessKey, secret);
            inputStream = file.getInputStream();
            PutObjectResult result = ossClient.putObject(bucket, objectKey, inputStream);

            if (result != null) {
                // 5. 上传成功，返回文件 URL
                String fileUrl = "https://" + bucket + "." + endpoint + "/" + objectKey;
                log.info("文件上传成功，URL: {}", fileUrl);
                return fileUrl;
            }
            return "上传失败";

        } catch (Exception e) {
            log.error("文件上传失败，异常信息: {}", e.getMessage());
            return "上传失败：服务异常";
        } finally {
            // 6. 确保关闭客户端和输入流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            } catch (IOException e) {
                log.error("关闭资源失败: {}", e.getMessage());
            }
        }
    }
}
